package com.iogogogo.supervisord4j;

import com.iogogogo.supervisord.annotation.EnableSupervisord;
import com.iogogogo.supervisord.exception.SupervisordException;
import com.iogogogo.supervisord.properties.SupervisordProperties;
import com.iogogogo.supervisord4j.properties.InstanceProperties;
import com.iogogogo.supervisord4j.service.SupervisordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.info.GitProperties;
import springfox.documentation.oas.annotations.EnableOpenApi;

import java.io.IOException;
import java.util.Map;

@Slf4j
@EnableOpenApi
@EnableSupervisord
@SpringBootApplication
public class Supervisord4jApplication implements CommandLineRunner {

    private final GitProperties gitProperties;

    private final SupervisordService supervisordService;

    private final InstanceProperties instanceProperties;

    public Supervisord4jApplication(GitProperties gitProperties, SupervisordService supervisordService, InstanceProperties instanceProperties) {
        this.gitProperties = gitProperties;
        this.supervisordService = supervisordService;
        this.instanceProperties = instanceProperties;
    }

    public static void main(String[] args) {
        SpringApplication.run(Supervisord4jApplication.class, args);
    }

    @Override
    public void run(String... args) {

        gitProperties.forEach(x -> log.info("gitProperties key:{}\tvalue:{}", x.getKey(), x.getValue()));

        Map<String, SupervisordProperties> instance = instanceProperties.getInstance();
        instance.keySet().forEach(x -> {
            try {
                supervisordService.saveJobList(x);
            } catch (SupervisordException | IOException e) {
                log.error(e.getMessage(), e);
            }
        });
        log.info("Supervisord4jApplication start completed.");
    }
}
